#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<conio.h>
struct telephone{
 	char name[20];
 	char phonenumber[20];
 	telephone *next;//定义一个指向结构类型的指针
};
void enter();
void del();
void list();
void search();
void save();
void load();

int main(){
	FILE *fp = fopen("books.txt", "r");
	int mode;
	

	do{
		printf("Choose your mode:\n\n");
		printf("0-退出通讯录\n");
		printf("1-通讯录录入\n");
		printf("2-通讯录删除\n");
		printf("3-通讯录显示\n");
		printf("4-通讯录查询\n");
		printf("5-通讯录保存\n");
		printf("6-通讯录加载\n");
		scanf("%d",&mode);
		switch(mode){
			case 0:	system("cls");
					printf("已退出");
				break;
			case 1:enter();
				break;
			case 2:del();
				break;
		}
	}while(mode != 0);
 	return 0;
 }
 
 void enter(){
 	fflush(stdin);
	telephone *head = NULL;//链表头
 	telephone *current, *ptr;//current表示当前链表，ptr是当前链表的前一个链表
	char input[20];
	system("cls");
	//输入联系人
		printf("请输入联系人姓名：\n");
		while (gets(input) != NULL&&input[0] != '\0'){
			current = (telephone*)malloc(sizeof(telephone));
			if (head == NULL){
			 	head = current;
			}
			else{
				ptr->next = current;
			}
			current->next = NULL;
			
 			strcpy(current->name,input);
			printf("请输入电话号码：\n");
			scanf("%s", current->phonenumber);
			printf("请输入下一个联系人（空格结束）：\n");
			
			while (getchar() == '\n'){
			 	continue;
			}
			ptr = current;
			}
		//写入联系人
		current = head;
		FILE *fp=fopen("book.txt","a");
		while (current != NULL){
			fprintf(fp,"%s %s\n",current->name,current->phonenumber);
			current = current->next;
		}
		//清除指针current的内存
		current = head;
		while (current != NULL){
		 	free(current);
			current = current->next;
		}
		fclose(fp);
		system("cls");
}

void del(){
	fflush(stdin);
	telephone *head = NULL;//链表头
 	telephone *current, *ptr;//current表示当前链表，ptr是当前链表的前一个链表
 	char id[20];
 	system("cls");
	FILE *fp = fopen("book.txt","r+");
	FILE *fp1 = fopen("book1.txt","w");
	head = current;
	
	printf("输入要删除的对象：");
	scanf("%s",&id);
//	printf("%s",id);
	
	while (current != NULL){
		current = (telephone*)malloc(sizeof(telephone));
		if (head == NULL){
		 	head = current;
		}	
		else{
			ptr->next = current;
		}
		current->next = NULL;
		
 		fscanf(fp,"%s",current->name);
 		fscanf(fp,"%s",current->phonenumber);
 		//fread(&current, sizeof(struct telephone),1,fp);
 		
		ptr = current;
	}
	rewind(fp);
	
	current = head;
	while (current != NULL){
//		if (strcmp(current->name, id) !=0){
			fprintf(fp1,"%s %s\n",current->name,current->phonenumber);
			//fwrite(&current, sizeof(struct telephone),1,fp);
			
//		}
		current = current->next;
	}
	current = head;
	while (current != NULL){
		free(current);
		current = current->next;
	}
	
	fclose(fp);
	fclose(fp1);
	remove("book.txt");
	rename("book1.txt","book.txt");
	printf("已删除");
}
